package com.scuec.groupfive.service.impl;

import com.scuec.groupfive.entity.UserInfo;
import com.scuec.groupfive.mapper.UserRegisterMapper;
import com.scuec.groupfive.service.UserRegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserRegisterServiceImpl implements UserRegisterService {

    @Autowired
    private UserRegisterMapper userRegisterMapper;

    @Override
    public boolean isUsernameExist(String username) {
        UserInfo user = userRegisterMapper.getUserByUsername(username);
        return user != null;
    }

    @Override
    @Transactional
    public Integer registerUser(String username, Integer examYear, String password, String phone) {
        // 检查用户名是否已存在
        if (isUsernameExist(username)) {
            throw new DuplicateKeyException("用户名已存在: " + username);
        }

        // 创建用户实体
        UserInfo user = new UserInfo();
        user.setUsername(username);
        user.setPassword(password);
        user.setExamYear(examYear);
        user.setPhone(phone);
        user.setStatus(1); // 设置默认状态
        user.setRole("student"); // 设置默认角色

        try {
            // 插入新用户 - 使用user对象
            int affectedRows = userRegisterMapper.insertUser(user);
            if (affectedRows > 0) {
                // 直接从user对象获取回填的ID
                return user.getUserId();
            }
            return null;
        } catch (Exception e) {
            throw new RuntimeException("用户注册失败: " + e.getMessage(), e);
        }
    }
}